
local LUtil = require 'packages/lingling/utility/_base'

local U = require "packages/utility/utility"

local Global = fk.CreateTriggerSkill{
  name = "#LingGlobal",
  global = true,
  priority = 2,

  refresh_events = {fk.AfterCardsMove, fk.AfterDrawPileShuffle, fk.AfterTurnEnd,
    fk.GamePrepared, fk.EventAcquireSkill, fk.EventLoseSkill,
    fk.DrawInitialCards, fk.AfterDrawInitialCards, fk.TurnStart,
    fk.HpChanged, fk.Damaged, fk.Death},
  can_refresh = function(self, event, target, player, data)
    if player.seat == 1 then
      if event == fk.DrawInitialCards then
        return #player.room.players > 6 and player.room:isGameMode("role_mode")
      elseif event == fk.TurnStart then
        return player.room:getTag("RoundCount") == 1 and target.seat > 6 and player.room:isGameMode("role_mode")
      elseif table.contains({fk.HpChanged, fk.Damaged, fk.Death}, event) then
        return player.room:isGameMode("1v2_mode")
      else
        return true
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    --七八号位增益
    if event == fk.DrawInitialCards then
      if target.seat == 7 then
        data.num = data.num + 1
      elseif target.seat == 8 then
        data.num = data.num + 2
      end
    elseif event == fk.TurnStart then
      room:handleAddLoseSkills(target, "m_feiyang", nil, false, true)
      room.logic:getCurrentEvent():findParent(GameEvent.Turn, true):addCleaner(function()
        room:handleAddLoseSkills(target, "-m_feiyang", nil, false, true)
      end)
    --地主护甲
    elseif event == fk.HpChanged then
      if target and data.reason == "damage" and data.shield_lost > 0 then
        local e = room.logic:getCurrentEvent():findParent(GameEvent.Damage)
        if e then
          local damage = e.data[1]
          damage.extra_data = damage.extra_data or {}
          damage.extra_data.shield_lost = data.shield_lost
        end
      end
    elseif event == fk.Damaged then
      if target.role == "lord" and data.extra_data and (data.extra_data.shield_lost or 0) > 0 then
        room.logic:getCurrentEvent():shutdown()
      end
    elseif event == fk.Death then
      local lord = room:getLord() or room.players[1]
      room:changeShield(lord, -5)
    else
      if event == fk.GamePrepared then
        if room:isGameMode("1v2_mode") then
          local lord = room:getLord() or room.players[1]
          room:changeShield(lord, 5)
        end
        for i = #room.draw_pile, 1, -1 do
          local id = room.draw_pile[i]
          local card = Fk:getCardById(id)
          --雌雄双股剑替换
          if card.name == "double_swords" then
            table.insert(room.void, id)
            room:setCardArea(id, Card.Void, nil)
            local new_card = room:printCard("ling__double_swords", Fk:getCardById(id).suit, Fk:getCardById(id).number)
            room.draw_pile[i] = new_card.id
            room:setCardArea(new_card.id, Card.DrawPile, nil)
          --方天画戟替换
          elseif card.name == "halberd" then
            table.insert(room.void, id)
            room:setCardArea(id, Card.Void, nil)
            local new_card = room:printCard("ling__modao", Fk:getCardById(id).suit, Fk:getCardById(id).number)
            room.draw_pile[i] = new_card.id
            room:setCardArea(new_card.id, Card.DrawPile, nil)
          --朱雀羽扇替换
          elseif card.name == "fan" then
            table.insert(room.void, id)
            room:setCardArea(id, Card.Void, nil)
            local new_card = room:printCard("ling__fire_gun", Fk:getCardById(id).suit, Fk:getCardById(id).number)
            room.draw_pile[i] = new_card.id
            room:setCardArea(new_card.id, Card.DrawPile, nil)
          --暂时移除乐不思蜀
          elseif card.name == "indulgence" then
            local tag = room.tag["ling_indulgence"] or {}
            table.insert(room.void, id)
            room:setTag("ling_indulgence", tag)
            table.insert(tag, id)
            room:setCardArea(id, Card.Void, nil)
            table.remove(room.draw_pile, i)
          end
        end
        room:syncDrawPile()
        room:doBroadcastNotify("UpdateDrawPile", tostring(#room.draw_pile))
      elseif event == fk.AfterDrawInitialCards then
        --乐不思蜀洗至牌堆后半
        local tag = room.tag["ling_indulgence"] or {}
        for _, id in ipairs(tag) do
          if room:getCardArea(id) == Card.Void then
            table.removeOne(room.void, id)
            table.insert(room.draw_pile, math.random(#room.draw_pile // 2, #room.draw_pile), id)
            room:setCardArea(id, Card.DrawPile, nil)
          end
        end
        room:setTag("ling_indulgence", nil)
        room:syncDrawPile()
        room:doBroadcastNotify("UpdateDrawPile", tostring(#room.draw_pile))
      end
      --中央区显示相关
      if event == fk.EventLoseSkill then
        room:setBanner("@$CenterArea", nil)
      elseif event == fk.AfterTurnEnd then
        room:setBanner("@$CenterArea", {})
      else
        local cards = {}
        room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
          for _, move in ipairs(e.data) do
            if move.toArea == Card.DiscardPile then
              for _, info in ipairs(move.moveInfo) do
                table.insertIfNeed(cards, info.cardId)
              end
            end
          end
        end, Player.HistoryTurn)
        cards = table.filter(cards, function (id)
          local card = Fk:getCardById(id)
          return table.contains(room.discard_pile, id) and
            table.every(MarkEnum.TempMarkSuffix, function (suffix)
            return card:getMark("RemoveCenterCards"..suffix) == 0
          end)
        end)
        room:setBanner("@$CenterArea", cards)
      end
    end
  end,
}
Fk:addSkill(Global)
Fk:loadTranslationTable{
  ["@$CenterArea"] = "中央区",
  ["$CenterArea"] = "中央区",
}

---@param player ServerPlayer 获得技能的角色（用于判断hasSkill）
---@param num integer 获得技能数
---@return string[] @返回获得技能名列表，可能为空
LUtil.GetRandomSkills = function (player, num)
  num = num or 1
  local skills = {}
  for _, general in pairs(Fk.generals) do
    if not general.hidden and not general.total_hidden then
      table.insertTableIfNeed(skills, general:getSkillNameList(true))
    end
  end
  skills = table.filter(skills, function (s)
    return not player:hasSkill(s, true)
  end)
  if #skills > 0 then
    return table.random(skills, num)
  end
end

return LUtil
